package com.gitee.wsl.doc.prosemirror.ui.command

import com.gitee.wsl.doc.prosemirror.model.content.ext.findCutAfter
import com.gitee.wsl.doc.prosemirror.model.content.ext.findCutBefore
import com.gitee.wsl.doc.prosemirror.state.Command
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.state.ext.joinTextblocksAround
import com.gitee.wsl.doc.prosemirror.ui.EditorView
import com.gitee.wsl.doc.prosemirror.ui.ext.atBlockEnd
import com.gitee.wsl.doc.prosemirror.ui.ext.atBlockStart

/**
 * 有限版本的向后合并命令，仅当光标位于文本块起始位置时，尝试将当前文本块与前一个文本块合并。
 * @param state 编辑器状态对象
 * @param dispatch 事务处理回调函数
 * @param view 视图对象
 * @return 操作是否成功执行
 */
val Command.Companion.joinTextblockBackward
    get() = JoinTextblockBackward

object JoinTextblockBackward: UiCommand{
    override fun exec(
        view: EditorView?,
        state: EditorState,
        dispatch: CommandDispatch?,
    ): Boolean {
        val cursor = atBlockStart(state, view) ?: return false
        val cut = cursor.findCutBefore()
        return if (cut != null) state.joinTextblocksAround( cut, dispatch) else false
    }
}


/**
 * 有限版本的向前合并命令，仅当光标位于文本块结束位置时，尝试将当前文本块与后一个文本块合并。
 * @param state 编辑器状态对象
 * @param dispatch 事务处理回调函数
 * @param view 视图对象
 * @return 操作是否成功执行
 */
val Command.Companion.joinTextblockForward
    get() = JoinTextblockForward

object JoinTextblockForward: UiCommand{
    override fun exec(
        view: EditorView?,
        state: EditorState,
        dispatch: CommandDispatch?,
    ): Boolean {
        val cursor = atBlockEnd(state, view) ?: return false
        val cut = cursor.findCutAfter()
        return if (cut != null) state.joinTextblocksAround(cut, dispatch) else false
    }
}

